import json
import os

def polygon_to_linestring(coordinates):
    """
    将多边形坐标转换为线段坐标
    
    参数:
    coordinates: 多边形的坐标列表
    
    返回:
    线段坐标列表
    """
    # 对于MultiPolygon,需要处理每个子多边形
    if isinstance(coordinates[0][0][0], list):
        lines = []
        for polygon in coordinates:
            # 获取外环坐标
            outer_ring = polygon[0]
            lines.append(outer_ring)
        return lines
    else:
        # 单个多边形,直接返回外环
        return [coordinates[0]]

def convert_polygon_to_line(input_file, output_file):
    """
    将GeoJSON面数据转换为线数据
    
    参数:
    input_file: 输入的面数据文件路径
    output_file: 输出的线数据文件路径
    """
    try:
        # 读取输入文件
        with open(input_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
            
        # 创建新的GeoJSON结构
        line_geojson = {
            "type": "FeatureCollection",
            "features": []
        }
        
        # 处理每个要素
        for feature in data['features']:
            geometry = feature['geometry']
            
            if geometry['type'] in ['Polygon', 'MultiPolygon']:
                # 获取所有线段
                lines = polygon_to_linestring(geometry['coordinates'])
                
                # 为每个线段创建一个新的要素
                for line in lines:
                    new_feature = {
                        "type": "Feature",
                        "properties": feature['properties'].copy(),
                        "geometry": {
                            "type": "LineString",
                            "coordinates": line
                        }
                    }
                    line_geojson['features'].append(new_feature)
            
        # 写入输出文件
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(line_geojson, f, ensure_ascii=False)
            
        print(f'转换完成！已将面数据转换为线数据并保存至: {output_file}')
        print(f'共转换 {len(line_geojson["features"])} 条线段')
        
    except Exception as e:
        print(f'转换过程中发生错误: {str(e)}')

if __name__ == '__main__':
    # 获取当前脚本所在目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 指定输入输出文件路径
    input_file = os.path.join(current_dir, 'geojson', 'L2_line.json')
    output_file = os.path.join(current_dir, 'geojson', 'L2_line2.json')
    
    # 执行转换
    convert_polygon_to_line(input_file, output_file)
